'use strict';
const
	colors = require('colors');

String.prototype.len = function() {
	return this.replace(/[^\x00-\xff]/g, '__').length;
}
String.prototype.pad = function(len, pattern = ' ') {
	return this + pattern.repeat(len - this.replace(/[^\x00-\xff]/g, '__').length);
}

String.prototype.padRight = function(len, pattern = ' ') {
	return this + pattern.repeat(len - this.replace(/[^\x00-\xff]/g, '__').length);
}

String.prototype.padLeft = function(len, pattern = ' ') {
	return pattern.repeat(len - this.replace(/[^\x00-\xff]/g, '__').length) + this;
}

function tableview(data, options){
	let _options = {
		header: false
	}
	Object.assign(_options, options);
	let _length = [];

	for(let item of data) {
		for(let i=0;i<item.length;i++){
			let s = String(item[i]);
			if (!_length[i]) _length[i] = 0;
			if (s != 'undefined') {
				let l = Math.max(_length[i], s.len());
				if (!isNaN(l)) _length[i] = l;
			}
		}
	}

	for(let j=0;j<data.length;j++) {
		let item = data[j];
		for(let i=0;i<item.length;i++) {
			let s = String(item[i]);
			let _s = s.padRight(_length[i]) + ' ';
			if (j == 0 && _options.header) _s = _s.cyan.bold;
			process.stdout.write(_s);
		}
		process.stdout.write('\n');
	}
}

module.exports = tableview;
